package com.wjk.cms.util;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;

@Slf4j
public class DingdingUtil {

    public static boolean send(String accessToken, String content, String atMobiles, String isAtAll) {
        boolean success = true;
        try {
            String serverUrl = "https://oapi.dingtalk.com/robot/send?access_token=" + accessToken;
            DingTalkClient client = new DefaultDingTalkClient(serverUrl);
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype("text");
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            text.setContent(content);
            request.setText(text);
            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();

            if ("1".equals(isAtAll)) {
                at.setIsAtAll("true");
            } else {
                if(StringUtils.isNotBlank(atMobiles)) {
                    String[] list = atMobiles.split(",");
                    at.setAtMobiles(Arrays.asList(list));
                }
                at.setIsAtAll("false");
            }
            request.setAt(at);
            client.execute(request);
        } catch (Exception e) {
            success = false;
            log.error("发送钉钉消息失败 - " + e.getMessage(), e);
        }
        return success;
    }

}
